package com.wang.service.impl;

import com.wang.entity.Detail;
import com.wang.mapper.DetailMapper;
import com.wang.service.DetailService;
import com.wang.utils.PageUtil;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Classname DetailServiceImpl
 * @Description TODO
 * @Date 2024/11/11 9:47
 * @Created by pc
 */
@Service
@Transactional
public class DetailServiceImpl implements DetailService {
    @Resource
    private DetailMapper detailMapper;
    public PageUtil<Detail> find(Integer sid, Integer pageNo, Integer pageSize) {
        PageUtil<Detail> pageUtil = new PageUtil<Detail>();
        Map<String,Object> map = new HashMap<String, Object>();
        map.put("sid",sid);
        map.put("pageIndex",(pageNo - 1) * pageSize); // 起始索引 = (页码数- 1) * 页大小
        map.put("pageSize",pageSize);
        List<Detail> details = detailMapper.find(map);
        pageUtil.setPageSize(pageSize);
        pageUtil.setCurrentPage(pageNo);
        pageUtil.setData(details);
        pageUtil.setTotalSize(detailMapper.findCount(map));
        return pageUtil;
    }

    public Detail findById(Long id) {
        return detailMapper.findById(id);
    }

    public Map<String, Object> update(Detail detailVo, Integer count) {
        Map<String,Object> map = new HashMap<String, Object>();
        // 先查询库存
        Detail detail = detailMapper.findById(detailVo.getId());
        // 修改数量
        if(detail.getRemaining() < count){
            map.put("code",400);
            map.put("msg","库存不足,无法购买");
        }else{
            detail.setRemaining(detail.getRemaining() - count);
            // 执行更新操作
            Integer result = detailMapper.update(detail);
            if(result > 0){
                map.put("code",200);
                map.put("msg","购买成功");
            }else{
                map.put("code",444);
                map.put("msg","购买失败");
            }
        }
        return map;
    }
}
